package com.clickpaas.governmentcloud.utils.entityutils;

import com.clickpaas.governmentcloud.common.ServerResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 接口入参切面类,环绕通知
 * 
 * @author quhongwei E-mail:quhongwei@cs91tech.com
 * @created 2020-09-17 下午5:02:47 
 * @version 1.0
 */
@Aspect
@Component
public class ConditionalNotEmptyAspect {
	
	public static final Logger logger = LoggerFactory.getLogger(ConditionalNotEmptyAspect.class);

	@Pointcut("@annotation(com.clickpaas.governmentcloud.utils.entityutils.ConditionalNotEmpty)")
	public void annotationPointcut() {
		
	}
	
	@Around("annotationPointcut()")
//	@Around("@annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping) || @annotation(org.springframework.web.bind.annotation.PutMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping )|| @annotation(org.springframework.web.bind.annotation.RequestMapping )")
	public ServerResponse<?> doAround(ProceedingJoinPoint joinPoint) {
		ServerResponse<?> serverResponse = ServerResponse.createError("失败");
		//切入点方法参数
        Object[] params = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法参数类型
        Class<?>[] paramsType = method.getParameterTypes();
        //循环参数
    	for(int i = 0; i < params.length; i++) {
    		Object param = params[i];
    		//参数是List
            if (param instanceof List) {
                List<?> list = (List<?>) param;
                for (int j = 0; j < list.size(); j++) {
                	Object l = list.get(j);
                	Class<?> classObj = l.getClass();
                	//反射所有字段
                    Field[] fieldslist = classObj.getDeclaredFields();
                    for(Field field : fieldslist){
                    	ConditionalNotEmpty conditionalNotEmpty = field.getAnnotation(ConditionalNotEmpty.class);
                        //如果字段上有自定义注解@ConditionalNotEmpty
                        if(conditionalNotEmpty != null){
                            field.setAccessible(true);
                            try {
                                Object obj = field.get(l);
                                if(obj == null || "".equals(obj.toString())) {
                                	Map<String, Object> resultMap = new HashMap<>();
                                	String fieldName = field.getName();
                                	String message = conditionalNotEmpty.errorMessage();
                                	logger.info("参数[" + i + "], 索引为[" + j + "]的元素, 字段" + fieldName + "" + message);
                                	resultMap.put("fieldName", fieldName);
                                	serverResponse = ServerResponse.createError("参数[" + i + "], 索引为[" + j + "]的元素, 字段" + fieldName + "" + message);
                                	return serverResponse;
                                }
//                                serverResponse = (ServerResponse<?>) joinPoint.proceed(params);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (Throwable e) {
                            	e.printStackTrace();
                            }
                        }
                    }
                }
            } else {//参数非list
                //获取该参数类型
                Class<?> clazz = paramsType[i];
                //反射所有字段
                Field[] fields = clazz.getDeclaredFields();
                for(Field field : fields){
                	ConditionalNotEmpty conditionalNotEmpty = field.getAnnotation(ConditionalNotEmpty.class);
                    //如果字段上有自定义注解@ValidateObj
                    if(conditionalNotEmpty != null){
                        field.setAccessible(true);
                        try {
                            Object obj = field.get(param);
                            if(obj == null || "".equals(obj.toString())) {
                            	Map<String, Object> resultMap = new HashMap<>();
                            	String fieldName = field.getName();
                            	String message = conditionalNotEmpty.errorMessage();
                            	logger.info("参数[" + i + "]中字段" + fieldName + "" + message);
                            	resultMap.put("fieldName", fieldName);
                            	serverResponse = ServerResponse.createError("参数[ " + i + "]中字段" + fieldName + "" + message);
                            	return serverResponse;
                            }
//                            serverResponse = (ServerResponse<?>) joinPoint.proceed(params);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (Throwable e) {
                        	e.printStackTrace();
                        }
                    }
                }
            }
    	}
    	try {
			serverResponse = (ServerResponse<?>) joinPoint.proceed(params);
		} catch (Throwable e) {
			
			e.printStackTrace();
		}
		return serverResponse;
	}
	
}
